package org.automated.realestatemanager.advertisementgetter;

import org.apache.log4j.Logger;
import org.automated.realestatemanager.parsers.AdvertisementParser;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.CssSelectorNodeFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

public class KharkivEstate extends AbstractAdvertisementGetter {

	private static final Logger log = Logger.getLogger(KharkivEstate.class);

	public void executeParcing(AdvertisementParser advParser) {
		advParser.setSource("nedvigimost.kharkov");
		final int pages = 4;

		try {
			Parser parser = null;
			for (int k = 1; k < pages; k++) {
				parser = new Parser(
						"http://www.nedvigimost.kharkov.ua/advert?page="
								+ k
								+ "&filter0=328&filter3=&filter4=&filter1[317]=317&filter2[420]=420");

				parser.setEncoding("utf-8");

				final NodeFilter odd = new CssSelectorNodeFilter(".odd");

				final NodeFilter even = new CssSelectorNodeFilter(".odd");

				NodeList nodeList = parser.parse(odd);
				nodeList.add(parser.parse(even));

				for (int i = 0; i < nodeList.size(); i++) {

					final Node node = nodeList.elementAt(i);
					String n = node.toHtml();

					n = n.replaceAll("<[^>]*>", " ");
					n = n.replaceAll("[\\s]{2,}", " ");

					log.debug("\n\n" + n);
					System.out.println("\n\n" + n);

					advParser.executeParcing(n);
				}

				try {
					Thread.sleep(1000l);
				} catch (final InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		} catch (final ParserException e) {
			e.printStackTrace();
		}
	}

}
